package com.moyq5.wifi.joystick;

import com.moyq5.wifi.joystick.worker.netty.handler.CommandEncoder;
import com.moyq5.wifi.joystick.worker.netty.handler.DiscardServerHandler;
import com.moyq5.wifi.joystick.worker.netty.handler.ServerEncoder;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;

public class NettyServerChannelFactory {
    private static final Map<String, SocketChannel> channels = new ConcurrentHashMap<>();

    private static final ChannelInitializer initializer = new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.closeFuture().addListener(future -> {
                channels.remove(ch.id().asLongText());
            });
            channels.put(ch.id().asLongText(), ch);
            ch.pipeline().addLast(new CommandEncoder(), new ServerEncoder(), new DiscardServerHandler());
        }
    };

    public static ChannelInitializer getInitialize() {
        return initializer;
    }

    public static Map<String, SocketChannel> getChannels() {
        return new HashMap<>(channels);
    }
}
